package ltd.smallwang.app.task;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import ltd.smallwang.infrastructure.exception.CommonErrorCode;
import ltd.smallwang.infrastructure.task.db.TaskMapper;
import ltd.smallwang.infrastructure.task.db.model.TaskPo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * The type Task security service.
 *
 * @author justd
 * @description 功能描述
 * @since 2024 -05-26 07:38
 */
@Service
@RequiredArgsConstructor
public class TaskSecurityService {

  private final TaskMapper taskMapper;

  /**
   * 横向越权校验
   *
   * @param taskId the task id
   */
  public void checkTask(Long taskId) {
    QueryWrapper<TaskPo> queryWrapper = new QueryWrapper<>();
    queryWrapper.lambda().eq(TaskPo::getId, taskId)
        .eq(TaskPo::getUserId, StpUtil.getLoginIdAsLong());
    Long count = taskMapper.selectCount(queryWrapper);
    if (count == 0) {
      throw new BizException(CommonErrorCode.LATERAL_PRIVILEGE_ESCALATION.getErrorCode(),
          CommonErrorCode.LATERAL_PRIVILEGE_ESCALATION.getErrorMessage());
    }
  }

  /**
   * 横向越权校验
   *
   * @param taskIdList the task id list
   */
  public void checkTasks(List<Long> taskIdList) {
    QueryWrapper<TaskPo> queryWrapper = new QueryWrapper<>();
    queryWrapper.lambda().in(TaskPo::getId, taskIdList)
        .eq(TaskPo::getUserId, StpUtil.getLoginIdAsLong());
    Long count = taskMapper.selectCount(queryWrapper);
    if (count != taskIdList.size()) {
      throw new BizException(CommonErrorCode.LATERAL_PRIVILEGE_ESCALATION.getErrorCode(),
          CommonErrorCode.LATERAL_PRIVILEGE_ESCALATION.getErrorMessage());
    }
  }
}
